package 栈.练习;
//逆波兰数的运算
import java.util.Stack;

public class Text_3 {
    public int evalRPN(String[] tokens){
        Stack<Integer> stack = new Stack<>();

        int num = 0;
        for(String s:tokens){
            //检查是不是运算符
            if(!isOperation(s)){
                //字符串类型变为整型
                stack.push(Integer.parseInt(s));
            }else{
                //取出栈里面的数据
                int x2 = stack.pop();
                int x1 = stack.pop();

                switch (s){
                    case "+":
                        num = x1+x2;
                        break;
                    case "-":
                        num = x1-x2;
                        break;
                    case "*":
                        num = x1*x2;
                        break;
                    case  "/":
                        num = x1/x2;
                        break;
                }
                //将运算后的结果返回栈内
                stack.push(num);
            }
        }
        //结果为栈内第一个元素
        return stack.peek();
    }
    public boolean isOperation(String s){
        if(s.equals("+")||s.equals("-")||s.equals("*")||s.equals("/")){
            return true;
        }
        return false;
    }
}
